// UTMTileSystem.js
const TileSystem = require('./TileSystem');
const proj4 = require('proj4');
const turf = require('@turf/turf');

class UTMTileSystem extends TileSystem {
    constructor(app, zone, hemisphere = 'N') {
        super();
        this.app = app;
        this.zone = zone; // e.g., "33T"
        this.hemisphere = hemisphere; // 'N' 或 'S'
        this.tileSize = 256; // 每个图幅的米数，例如100,000米（100km）

        // 定义投影字符串
        const utmProj = `+proj=utm +zone=${this.zone} +${this.hemisphere === 'N' ? 'north' : 'south'} +ellps=WGS84 +datum=WGS84 +units=m +no_defs`;
        this.proj = proj4(utmProj, 'WGS84');
    }

    latLngToUTM(lat, lng) {
        return proj4('WGS84', this.proj, [lng, lat]);
    }

    utmToTile(utmX, utmY) {
        const tileX = Math.floor(utmX / this.tileSize);
        const tileY = Math.floor(utmY / this.tileSize);
        return { x: tileX, y: tileY };
    }

    calculateTileCoverage(centerLat, centerLng, zoom, imageWidth, imageHeight, scale) {
        const groundWidth = imageWidth * scale;
        const groundHeight = imageHeight * scale;

        const centerUTM = this.latLngToUTM(centerLat, centerLng);
        const [centerX, centerY] = centerUTM;

        const neUTM = [centerX + groundWidth / 2, centerY + groundHeight / 2];
        const swUTM = [centerX - groundWidth / 2, centerY - groundHeight / 2];

        const neTile = this.utmToTile(neUTM[0], neUTM[1]);
        const swTile = this.utmToTile(swUTM[0], swUTM[1]);

        const tileRange = {
            minX: Math.min(neTile.x, swTile.x),
            maxX: Math.max(neTile.x, swTile.x),
            minY: Math.min(neTile.y, swTile.y),
            maxY: Math.max(neTile.y, swTile.y)
        };

        return tileRange;
    }

    getTileBounds(tileX, tileY, zoom) {
        const minX = tileX * this.tileSize;
        const minY = tileY * this.tileSize;
        const maxX = (tileX + 1) * this.tileSize;
        const maxY = (tileY + 1) * this.tileSize;

        // 转换回经纬度
        const nw = proj4(this.proj, 'WGS84', [minX, maxY]); // 西北角
        const se = proj4(this.proj, 'WGS84', [maxX, minY]); // 东南角

        return { nw: { lat: se[1], lng: nw[0] }, se: { lat: nw[1], lng: se[0] } };
    }
}

module.exports = UTMTileSystem;
